﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace TaskProgramming
{
    class _004_Cancellation
    {
        public static void Test()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            var ct = cts.Token;

            var task = Task.Factory.StartNew(() =>
            {
                for (var i = 0; i < 20; i++)
                {
                    Thread.Sleep(500);

                    ct.ThrowIfCancellationRequested();
                    Console.WriteLine(i);
                }
            }, ct);

            Console.WriteLine("输入 Enter 键取消计数");
            Console.ReadLine();
            cts.Cancel();

            Thread.Sleep(1000);

            try
            {
                task.Wait();
            }
            catch(AggregateException ex)
            {
                Console.WriteLine(ex.InnerException.GetType());
                Console.WriteLine("IsCanceled:" + task.IsCanceled);
                Console.WriteLine("IsCompleted:" + task.IsCompleted);
                Console.WriteLine("IsFaulted:" + task.IsFaulted);
            }
        }
    }
}
